//
//  driveDetialVC.m
//  jiaKaoZhuShou
//
//  Created by 金艺社 on 2018/5/16.
//  Copyright © 2018年 金艺社. All rights reserved.
//

#import "driveDetialVC.h"
#import "pictureCell.h"
#import "detialSectionHeadView.h"
#import "evaluationCell.h"
#import "signUpVC.h"//舍去
#import "selectInstallmentView.h"
#import "evaluationModel.h"
#import "driveSchoolModel.h"
#import "installmentModel.h"
#import "logInVCViewController.h"
#import "realNameVC.h"
@interface driveDetialVC () <UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate> {
    installmentModel *modelll;
    driveSchoolModel *model;
}
@property (nonatomic, strong) UITableView *detialView;
@property (nonatomic, strong) NSMutableArray *evaluationList;
@property (nonatomic, strong) NSMutableArray *driveDetial;
@end

@implementation driveDetialVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"驾校详情";
    self.view.backgroundColor = [UIColor whiteColor];
    CGRect frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - StatusBarAndNavigationBarHeight - TabbarSafeBottomMargin - 50);
    self.detialView = [[UITableView alloc]initWithFrame:frame style:UITableViewStylePlain];
//    self.detialView = [[UITableView alloc]initWithFrame:frame];
    if (@available(iOS 11.0, *)) {
        self.detialView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
//        if (iPhoneX) {
//            self.detialView.contentInset = UIEdgeInsetsMake(0, 0, 88, 0);
//        }else {
//            self.detialView.contentInset = UIEdgeInsetsMake(0, 0, 64, 0);
//        }
//        self.detialView.scrollIndicatorInsets = self.detialView.contentInset;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.detialView.delegate = self;
    self.detialView.dataSource = self;
    [self.detialView registerNib:[UINib nibWithNibName:NSStringFromClass([pictureCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([pictureCell class])];
    [self.detialView registerNib:[UINib nibWithNibName:NSStringFromClass([evaluationCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([evaluationCell class])];
    self.detialView.tableFooterView = [UIView new];
    [self addBootomBtn];
    [self driveDetialRequest];
}

#pragma mark --- uitableViewDelegate and dataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.evaluationList.count == 0 ? 2 : 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 2) {
       return  self.evaluationList.count >= 3 ? 3 : self.evaluationList.count;
    }
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) return 0;
    return 40;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {
        CGFloat cellHeight = 13;
        driveSchoolModel *model = [self.driveDetial objectAtIndex:indexPath.row];
        cellHeight += [model.introduction boundingRectWithSize:CGSizeMake(kScreenWidth - 6, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:13]} context:nil].size.height;
        return cellHeight;
    }else if (indexPath.section == 2) {
        CGFloat cellHeight = 65;
        evaluationModel *model = [self.evaluationList objectAtIndex:indexPath.row];
        cellHeight += [model.apprais boundingRectWithSize:CGSizeMake(kScreenWidth - 50, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:11]} context:nil].size.height;
        return cellHeight;
    }
    return 225;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([UITableViewCell class])];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass([UITableViewCell class])];
            [self setCellBackColor:cell];
            UILabel *lab = [UILabel new];
            lab.tag = viewTag1;
            lab.font = [UIFont customFontOfSize:13];
            lab.numberOfLines = 0;
            [cell.contentView addSubview:lab];
            [lab mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(@13);
                make.right.equalTo(@-10);
                make.top.equalTo(@1);
                make.bottom.equalTo(@-3);
            }];
        }
        UILabel *contentLab = (UILabel *)[cell viewWithTag:viewTag1];
        driveSchoolModel *model = [self.driveDetial objectAtIndex:indexPath.row];
        contentLab.text = model.introduction;
        return cell;
    }else if (indexPath.section == 2) {
        evaluationCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([evaluationCell class])];
        evaluationModel *model = [self.evaluationList objectAtIndex:indexPath.row];
        cell.model = model;
        [self setCellBackColor:cell];
        return cell;
    }
    pictureCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([pictureCell class])];
    [cell.locationBtn addTarget:self action:@selector(location) forControlEvents:UIControlEventTouchUpInside];
    cell.model = [self.driveDetial objectAtIndex:indexPath.row];
    cell.distance_lab.text = [NSString stringWithFormat:@"距您%.2f千米", self.distance.floatValue];;
    [self setCellBackColor:cell];
    cell.accessoryType = UITableViewCellAccessoryNone;
    return cell;
}
- (void)setCellBackColor:(UITableViewCell *)cell {
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 0) return nil;
    if (section == 2) {
        detialSectionHeadView *view = [[detialSectionHeadView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 40)];
        [view setTitle:@"驾校评价"];
        if (self.evaluationList.count > 3) {
            enum ViewType type = right;
            UIButton *customBtn = [UIButton titleOnLeftOfContentWithTitle:@"更多>>" andTitleColorString:@"#4398F3" andFont:12 andImageStr:@"" andContainerView:view andLocation:type andTitleOnLeft:YES andBackColor:@""];
        }
        return view;
    }
    detialSectionHeadView *view = [[detialSectionHeadView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 40)];
    [view setTitle:@"驾校简介"];
    return view;
}

#pragma mark --- addSubView
- (void)addBootomBtn {
    enum ViewType type = bottom;
    UIButton *customBtn = [UIButton titleOnLeftOfContentWithTitle:@"立即报名" andTitleColorString:@"#FFFFFF" andFont:15 andImageStr:@"signUp" andContainerView:self.view andLocation:type andTitleOnLeft:NO andBackColor:@"#A91E23"];
}
#pragma mark --- bottomViewAction:
- (void)bottomViewAction:(id)sender {
    if (USERTOKEN == nil) {
        [self logInVC];
        return;
    }
    [self isReal_nameAuthentication];
}
- (void)logInVC {
    logInVCViewController *VC = [logInVCViewController new];
    VC.btnHidden = @"NO";
    [self presentViewController:VC animated:YES completion:nil];
}
#pragma mark --- detial
- (void)driveDetialRequest {
    __weak driveDetialVC *wf = self;
    NSString *url = [NSString stringWithFormat:@"%@%@", [[apiManger shareApiManger] driveDetial], self.ID];
    [networkManger PostHttpDataWithUrlStr:url Dic:nil SuccessBlock:^(id responseObject) {
        if ([responseObject[@"rcd"] isEqualToString:R0001]) {
            wf.evaluationList = [evaluationModel mj_objectArrayWithKeyValuesArray:responseObject[@"result"][@"result"]];
            model = [driveSchoolModel mj_objectWithKeyValues:responseObject[@"data"]];
            if ([model.introduction isEqualToString:@""]) {
                model.introduction = @"敬请期待！";
            }
            [wf.driveDetial addObject:model];
            [wf.view addSubview:self.detialView];
        }else {
            [MBProgressHUD gk_toastShowMessage:responseObject[@"rmg"]];
        }
    } FailureBlock:^(id error) {
        [MBProgressHUD gk_toastShowMessage:@"请求失败"];
    }];
}
// 判断实名认证
- (void)isReal_nameAuthentication {
    __weak driveDetialVC *wf = self;
    NSDictionary *dic = @{
                          @"token":USERTOKEN
                          };
    NSString *url = [NSString stringWithFormat:@"%@", [[apiManger shareApiManger] isShiMingRenZheng]];
    [networkManger PostHttpDataWithUrlStr:url Dic:dic SuccessBlock:^(id responseObject) {
        if ([responseObject[@"rcd"] isEqualToString:R0001]) { //已认证
            NSString *status = [NSString stringWithFormat:@"%@", responseObject[@"status"]];
            if ([status isEqualToString:@"1"]) {
                [wf installmentRequest];
                return;
            }
        }
        //未认证，去认证
        realNameVC *VC = [realNameVC new];
        [self.navigationController pushViewController:VC animated:YES];
        
    } FailureBlock:^(id error) {
        [MBProgressHUD gk_toastShowMessage:@"请求失败"];
    }];
}
//分期
- (void)installmentRequest {
    __weak driveDetialVC *wf = self;
    NSDictionary *dic = @{
                          @"token":USERTOKEN,
                          };
    NSString *url = [NSString stringWithFormat:@"%@%@", [[apiManger shareApiManger] installment], self.ID];
    [networkManger PostHttpDataWithUrlStr:url Dic:dic SuccessBlock:^(id responseObject) {
        if ([responseObject[@"rcd"] isEqualToString:R0001]) {
            modelll = [installmentModel mj_objectWithKeyValues:responseObject];
            [wf addInstallmentView];
        }else if ([responseObject[@"rmg"] isEqualToString:@"用户不存在"]){
            [MBProgressHUD gk_toastShowMessage:responseObject[@"rmg"]];
            [wf logInVC];
        }else {
            [MBProgressHUD gk_toastShowMessage:responseObject[@"rmg"]];
        }
    } FailureBlock:^(id error) {
        [MBProgressHUD gk_toastShowMessage:@"请求失败"];
    }];
}

- (void)addInstallmentView {
    selectInstallmentView *View = [[selectInstallmentView alloc]initWithFrame:CGRectMake(0, kScreenHeight, kScreenWidth, 0)];
    [self.view addSubview:View];
    [UIView animateWithDuration:0.3 animations:^{
        View.frame = CGRectMake(0, kScreenHeight - StatusBarAndNavigationBarHeight - TabbarSafeBottomMargin - 270, kScreenWidth, 270);
    } completion:^(BOOL finished) {
        [View setModel:modelll];
    }];
}
#pragma mark ---- getter
- (NSMutableArray *)evaluationList {
    if (!_evaluationList) {
        _evaluationList = [NSMutableArray array];
    }
    return _evaluationList;
}
- (NSMutableArray *)driveDetial {
    if (!_driveDetial) {
        _driveDetial = [NSMutableArray array];
    }
    return _driveDetial;
}

- (void)location {
    if (self.locationBlk) {
        self.locationBlk(model.companyName);
        [self.navigationController popViewControllerAnimated:YES];
    }
}
- (void)dealloc {
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
